//
//  JDCityUnionListTableViewCell.swift
//  DragonWallet
//
//  Created by volantPig on 2024/4/2.
//

import UIKit

class JDCityUnionListTableViewCell: UITableViewCell {

    var dragonUnionModel: DragonUnionListModel? {
        didSet {
            self.refreshDataNew()
        }
    }
    
    var containerView: UIView?
    var titleStrLabel: UILabel?
    var contentLabel: UILabel?
    var middleLine: UIView?
    var removeButton: UIButton?
    
    var callButtonContainerView: UIStackView?
    var callButton: UIButton?
    
    var userPortraitImageV: UIImageView?
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.contentView.backgroundColor = color("#F5F6F8")
//        self.setupUIElements()
        self.setupUIElementsNew()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUIElementsNew() {
        
        self.containerView = UIView()
        self.contentView.addSubview(self.containerView!)
        self.containerView?.snp.makeConstraints { make in
            make.leading.equalTo(self.contentView).offset(12)
            make.trailing.equalTo(self.contentView).offset(-12)
            make.top.equalTo(self.contentView)
            make.bottom.equalTo(self.contentView).offset(-10)
        }
        self.containerView?.backgroundColor = .white
        self.containerView?.layer.cornerRadius = 8
        
        self.userPortraitImageV = UIImageView()
        self.containerView?.addSubview(self.userPortraitImageV!)
        self.userPortraitImageV?.snp.makeConstraints { make in
            make.leading.equalTo(self.containerView!).offset(12)
            make.centerY.equalTo(self.containerView!)
            make.size.equalTo(CGSizeMake(36, 36))
        }
        self.userPortraitImageV?.layer.cornerRadius = 18
        self.userPortraitImageV?.clipsToBounds = true
        self.userPortraitImageV?.image = UIImage(named: "userPortraiPlaceholder_small")
        
        self.titleStrLabel = UILabel()
        self.containerView?.addSubview(self.titleStrLabel!)
        self.titleStrLabel?.snp.makeConstraints { make in
            make.leading.equalTo(self.userPortraitImageV!.snp.trailing).offset(10)
            make.centerY.equalTo(self.userPortraitImageV!)
        }
        self.titleStrLabel?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 16, weight: .medium), textColor: color("#333333"))
        self.titleStrLabel?.text = "巴布豆儿童服务中心"
        
        
        self.removeButton = UIButton(type: .custom)
        self.containerView?.addSubview(self.removeButton!)
        self.removeButton?.snp.makeConstraints { make in
            make.trailing.equalTo(self.containerView!).offset(-12)
            make.centerY.equalTo(self.containerView!)
            make.size.equalTo(CGSize(width: 32, height: 32))
        }
        self.removeButton?.setImage(UIImage(named: "remove_DragonUnion")?.withRenderingMode(.alwaysOriginal), for: .normal)
        self.removeButton?.addTarget(self, action: #selector(removeAction), for: .touchUpInside)
        
        self.callButton = UIButton(type: .custom)
        self.containerView?.addSubview(self.callButton!)
        self.callButton?.snp.makeConstraints { make in
            make.centerY.equalTo(self.containerView!)
            make.trailing.equalTo(self.removeButton!.snp.leading).offset(-8)
            make.size.equalTo(CGSize(width: 32, height: 32))
        }
        self.callButton?.setImage(UIImage(named: "call_DragonUnion")?.withRenderingMode(.alwaysOriginal), for: .normal)
        self.callButton?.addTarget(self, action: #selector(callAction), for: .touchUpInside)
    }
    
    func refreshDataNew() {
        guard let currentModel = self.dragonUnionModel else { return }
        self.titleStrLabel?.text = currentModel.nickname
        self.userPortraitImageV?.downloadImage(currentModel.headerImg ?? "", "userPortraiPlaceholder_small")
    }
    
    func setupUIElements() {
        self.containerView = UIView()
        self.contentView.addSubview(self.containerView!)
        self.containerView?.snp.makeConstraints({ make in
            make.left.equalTo(self.contentView).offset(12)
            make.right.equalTo(self.contentView).offset(-12)
            make.top.equalTo(self.contentView)
            make.bottom.equalTo(self.contentView).offset(-10)
        })
        self.containerView?.backgroundColor = .white
        self.containerView?.layer.cornerRadius = 8
        
        self.titleStrLabel = UILabel()
        self.containerView?.addSubview(self.titleStrLabel!)
        self.titleStrLabel?.snp.makeConstraints({ make in
            make.left.equalTo(self.containerView!).offset(12)
            make.top.equalTo(self.containerView!).offset(15)
            make.height.greaterThanOrEqualTo(22)
        })
        self.titleStrLabel?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 16, weight: .medium), textColor: color("#333333"))
        self.titleStrLabel?.text = "巴布豆儿童服务中心"
        
        self.contentLabel = UILabel()
        self.containerView?.addSubview(self.contentLabel!)
        self.contentLabel?.snp.makeConstraints({ make in
            make.left.equalTo(self.containerView!).offset(12)
            make.top.equalTo(self.titleStrLabel!.snp.bottom).offset(5)
            make.right.equalTo(self.containerView!).offset(-56)
            make.height.greaterThanOrEqualTo(22)
        })
        self.contentLabel?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 16, weight: .regular), textColor: color("#333333"), numberOfLines: 0)
        self.contentLabel?.text = "教育服务|教育服务|教育服务|教育服务|教育服务|教育服务|教育服务|教育服务|教育服务|教育服务|教育服务|教育服务|教育服务|教育服务|教育服务"
        
        self.middleLine = UIView()
        self.containerView?.addSubview(self.middleLine!)
        self.middleLine?.snp.makeConstraints({ make in
            make.left.equalTo(self.containerView!).offset(12)
            make.right.equalTo(self.containerView!).offset(-12)
            make.top.equalTo(self.contentLabel!.snp.bottom).offset(14)
            make.height.equalTo(1)
        })
        self.middleLine?.backgroundColor = color("#F5F6F8")
        
        self.removeButton = UIButton(type: .custom)
        self.containerView?.addSubview(self.removeButton!)
        self.removeButton?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.containerView!)
            make.top.equalTo(self.middleLine!.snp.bottom)
            make.bottom.equalTo(self.containerView!)
            make.height.equalTo(47)
            
        })
        self.removeButton?.setTitle("移出", for: .normal)
        self.removeButton?.setTitleColor(color("#333333"), for: .normal)
        self.removeButton?.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        self.removeButton?.titleLabel?.textColor = color("#333333")
        self.removeButton?.addTarget(self, action: #selector(removeAction), for: .touchUpInside)
        
        self.callButtonContainerView = UIStackView()
        self.containerView?.addSubview(self.callButtonContainerView!)
        self.callButtonContainerView?.snp.makeConstraints({ make in
            make.right.equalTo(self.containerView!).offset(-12)
            make.top.equalTo(self.containerView!)
            make.bottom.equalTo(self.middleLine!.snp.top)
            make.width.equalTo(32)
        })
        self.callButtonContainerView?.axis = .horizontal
        self.callButtonContainerView?.distribution = .equalSpacing
        self.callButtonContainerView?.alignment = .center
        self.callButtonContainerView?.translatesAutoresizingMaskIntoConstraints = false
        
        self.callButton = UIButton(type: .custom)
        self.callButton?.frame = CGRect(x: 0, y: 0, width: 32, height: 32)
        self.callButton?.setImage(UIImage(named: "call_image")?.withRenderingMode(.alwaysOriginal), for: .normal)
        self.callButtonContainerView?.addArrangedSubview(self.callButton!)
        self.callButton?.addTarget(self, action: #selector(callAction), for: .touchUpInside)
    }
    
    @objc func callAction() {
        printLog("拨打电话:\(self.dragonUnionModel?.mobile)")
        
        let callStr = String.init(format: "tel:%@", self.dragonUnionModel?.mobile ?? "")
        if let callUrl = URL(string: callStr) {
            UIApplication.shared.open(callUrl, options: [:]) { isSuccess in
            }
        }
    }
    
    @objc func removeAction() {
        printLog("移除按钮")
        
        let popupConfirmView = JDPopupConfirmView()
        popupConfirmView.titleStr = String.init(format: "确定将 %@ 移除尨商圈吗？", self.dragonUnionModel?.nickname ?? "")//"确定将 巴布豆儿童服务中心 移除龙商圈吗？"
        popupConfirmView.confirmButtonSelected = {[weak self] in
            printLog("我点击了 移出 按钮")
            
            
            var params = [String: Any]()
            params["userId"] = self?.dragonUnionModel?.followingUserId
            
            JDNetWorkRequest(.removeDragonUnion(params)) { responseStr in
                
                let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
                
                if commonModel?.code == "0" {
                    JDSingle.default.needRefreshDragonBoard = true
                    JDTools.getKeyWindows()?.toast(message: "移除成功")
                    NotificationCenter.default.post(name: NSNotification.Name.init("refreshDragonUnionList"), object: nil)
                    
                } else if commonModel?.code == "01" {
                    // 错误
                } else if commonModel?.code == "401" {
                    // 未登录
                    
//                    if let loginModel = JDLoginModel.deserialize(from: responseStr, designatedPath: "data") {
//                        JDLoginModel.default.refreshData(loginModel)
//                        printLog("当前用户username:\(loginModel.nickname)")
//                        UserDefaults.standard.set(responseStr, forKey: "loginInfo")
//                        self.dismiss(animated: true)
//                    }
                    
                }
                
            } failure: { error in
                
            } error: { errorCode in
                
            }
        }
        JDTools.getKeyWindows()?.rootViewController?.view.addSubview(popupConfirmView)
        
    }
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    func refreshData() {
        
        guard let currentModel = self.dragonUnionModel else { return }
        self.titleStrLabel?.text = currentModel.nickname
        self.contentLabel?.text = currentModel.typeNameList?.joined(separator: "|")
        
    }
}
